package com.recipedb.recipedb.service.impl;

import com.recipedb.recipedb.entity.Likes;
import com.recipedb.recipedb.entity.LikesId;
import com.recipedb.recipedb.repository.LikesRepository;
import com.recipedb.recipedb.service.LikesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class LikesServiceImpl implements LikesService {

    @Override
    public void deleteByUserIdAndRecipeId(Long userId, Long recipeId) {
        repository.findByUserIdAndRecipeId(userId, recipeId)
        .ifPresent(repository::delete);
    }

    @Autowired
    private LikesRepository repository;

    @Override
    public Likes save(Likes entity) {
        return repository.save(entity);
    }

    @Override
    public void deleteById(LikesId id) {
        repository.deleteById(id);
    }

    @Override
    public Optional<Likes> findById(LikesId id) {
        return repository.findById(id);
    }

    @Override
    public List<Likes> findAll() {
        return repository.findAll();
    }

    @Override
    public List<Likes> findByUserId(Long userId) {
        return repository.findAll().stream()
                .filter(like -> like.getUserId().equals(userId))
                .collect(Collectors.toList());
    }

    @Override
    public List<Likes> findByRecipeId(Long recipeId) {
        // 直接调用Repository的排序方法
        return repository.findByRecipeIdOrderByCreatedAtDesc(recipeId);
    }

    @Override
    public boolean existsByUserIdAndRecipeId(Long userId, Long recipeId) {
        return repository.findAll().stream()
                .anyMatch(like -> like.getUserId().equals(userId) &&
                        like.getRecipeId().equals(recipeId));
    }

    @Override
    public List<Likes> findRecentLikesByUserId(Long userId, int limit) {
        return repository.findAll().stream()
                .filter(like -> like.getUserId().equals(userId))
                .sorted((l1, l2) -> l2.getCreatedAt().compareTo(l1.getCreatedAt()))
                .limit(limit)
                .collect(Collectors.toList());
    }
}